/**
 * 
 */
package com.none.web.service.beacon.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;
import com.none.web.model.TBeacon;
import com.none.web.model.TNews;
import com.none.web.model.TUser;
import com.none.web.service.beacon.IBeaconService;
import com.none.web.service.comments.ICommentsService;
import com.none.web.service.logs.ILogsService;

/**
 * Beacon Service实现
 * 
 * @author Summer
 */
@Service("beaconService")
public class BeaconServiceImpl extends BaseServiceSupport implements IBeaconService {
	@Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
	ILogsService logService;
    @Autowired
    ICommentsService  commentsService;
	@Override
	public Object addBeacon(TBeacon beacon, String newsId, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 判断用户
		TUser tuser = findEntity(TUser.class, userId);
		if (tuser == null) {
			throw new ValidateException("user.userUnExist");
		}

		// if (tuser.getRole().indexOf("Console Admin") == -1) {
		// throw new ValidateException("user.userIsNotRole");
		// }

		// 判断beacon属性值
		if (StringUtils.isBlank(beacon.getProximityUUID())) {
			throw new ValidateException("beacon.proximityUUIDNull");
		}
		if (StringUtils.isBlank(beacon.getMajor())) {
			throw new ValidateException("beacon.majorNull");
		}
		if (StringUtils.isBlank(beacon.getMinor())) {
			throw new ValidateException("beacon.minorNull");
		}
		if (StringUtils.isBlank(newsId)) {
			throw new ValidateException("beacon.newsIdIsNull");
		}
		if (beacon.getActive() == null) {
			throw new ValidateException("beacon.activeIsNull");
		}
		if (beacon.getIn_distance() == null) {
			throw new ValidateException("beacon.distanceIsNull");
		}
		if (StringUtils.isBlank(beacon.getPop_message())) {
			throw new ValidateException("beacon.popMessageIsNull");
		}
		if ("".equals(beacon.getSendNum())||beacon.getSendNum()==null) {
			throw new ValidateException("beacon.sendNumIsNull");
		}
		//校验新闻ID数据格式是否正确，只能是整数
		Integer newsId_int=null;
		try{
			newsId_int=Integer.parseInt(newsId);
		}catch(Exception e){
			throw new ValidateException("beacon.newsIdError");
		}
		// 判断绑定的新闻
		TNews tNews = findEntity(TNews.class, newsId_int);
		if (tNews == null) {
			throw new ValidateException("beacon.newsIsNull");
		}
		// 新闻不是审核通过
		if (!"Published".equals(tNews.getStatus())) {
			throw new ValidateException("beacon.newsIsNotPublished");
		}
		// 设置主键的值
		beacon.setBeaconId(CreateID.getID());
		// 设置ibeaconId
		beacon.setiBeaconId(beacon.getProximityUUID() + " " + beacon.getMajor() + " " + beacon.getMinor());
		// 设置绑定新闻
		beacon.setTnews(tNews);
		// 保存beacon的值
		if (saveEntity(beacon) == null) {
			throw new ValidateException("common.illegalRequest");
		} else {
			// if (!"announcement".equals(tNews.getType())) {
			// tNews.setType("announcement");
			// updateEntity(tNews);
			// }
			return beacon;
		}
	}

	@Override
	public Object listBeacon() {
		Criteria criteria = getCriteria(TBeacon.class);
		return listQBC(criteria);
	}

	@Override
	public Object searchBeacon(Pager pager, String ibeaconId, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");
        
		// 判断用户
		TUser tuser = findEntity(TUser.class, userId);
		if (tuser == null) {
			throw new ValidateException("user.userUnExist");
		}

		// if (tuser.getRole().indexOf("Console Admin") == -1) {
		// throw new ValidateException("user.userIsNotRole");
		// }
		
		Criteria criteria = getCriteria(TBeacon.class);
		if (StringUtils.isNotBlank(ibeaconId)) {
			criteria.add(Restrictions.ilike("iBeaconId", "%"+ibeaconId+"%"));
		}
		return listPageQBCL(criteria, pager);
	}

	@Override
	public Object listNews(TBeacon beacon, String userId) throws Exception {

		if (StringUtils.isBlank(beacon.getProximityUUID())) {
			throw new ValidateException("beacon.proximityUUIDNull");
		}
		if (StringUtils.isBlank(beacon.getMajor())) {
			throw new ValidateException("beacon.majorNull");
		}
		if (StringUtils.isBlank(beacon.getMinor())) {
			throw new ValidateException("beacon.minorNull");
		}

		Criteria criteria = getCriteria(TBeacon.class);

		criteria.add(Restrictions.eq("proximityUUID", beacon.getProximityUUID()));
		criteria.add(Restrictions.eq("major", beacon.getMajor()));
		criteria.add(Restrictions.eq("minor", beacon.getMinor()));

		List<?> beaconList = criteria.list();
		TNews news = new TNews();
		if (beaconList.size() == 1) {
			news= ((TBeacon) beaconList.get(0)).getTnews();
			
			//设置点赞数量   Add by Bing 2015-07-07
			String likeSql="select count(t.id) num from t_like t where  t.contentId='"+news.getNewsId()+"'";
			List<Map<String, Object>> listMapLike=this.jdbcTemplate.queryForList(likeSql);
			if(listMapLike!=null && listMapLike.size()>0){
				news.setLikeAmount(StringUtil.toInteger(listMapLike.get(0).get("num")));
			}else{
				news.setLikeAmount(0);
			}
			
			//设置当前用户是否对该信息点过赞  Add by Bing 2015-07-07
			String islikeSql="select count(t.id) num from t_like t where  t.contentId='"+news.getNewsId()+"' and t.userId='"+userId+"'";
			List<Map<String, Object>> listMapIsLike=this.jdbcTemplate.queryForList(islikeSql);
			Integer amount=0;
			if(listMapIsLike!=null && listMapIsLike.size()>0){
				amount=StringUtil.toInteger(listMapIsLike.get(0).get("num"));
			}else{
				amount=0;
			}
			if(amount>0){
				news.setLike(true);
			}else{
				news.setLike(false);
			}
			
			//设置浏览数量  Add by Bing 2015-07-07
			news.setBrowseTimes(logService.getBrowseTimes(news.getNewsId()+"", "", userId));
			
			//设置浏览数量(同一人浏览几次算几次)  Add by Bing 2015-07-07
			news.setAllBrowseTimes(logService.getAllBrowseTimes(news.getNewsId()+"", "", userId));
			
			
			//设置评论数量  Add by Bing 2015-07-07
			news.setCommentAmount(commentsService.getCommentsAmount(news.getNewsId()+"", ""));
		}
		return news;
	}

	@Override
	public Object editBeacon(TBeacon beacon, String newsId, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 判断用户
		TUser tuser = findEntity(TUser.class, userId);
		if (tuser == null) {
			throw new ValidateException("user.userUnExist");
		}
		
		// if (tuser.getRole().indexOf("Console Admin") == -1) {
		// throw new ValidateException("user.userIsNotRole");
		// }
		
		TBeacon tBeacon = null;
		if (beacon != null && StringUtils.isNotBlank(beacon.getBeaconId())) {
			tBeacon = findEntity(TBeacon.class, beacon.getBeaconId());
			if (tBeacon != null) {
				tBeacon.setiBeaconId(beacon.getProximityUUID() + " " + beacon.getMajor() + " " + beacon.getMinor());
				if (beacon.getOut_distance() != null) {
					tBeacon.setOut_distance(beacon.getOut_distance());
				}
				if (StringUtils.isNotBlank(beacon.getPop_image())) {
					tBeacon.setPop_image(beacon.getPop_image());
				}
				if (StringUtils.isNotBlank(beacon.getPop_times())) {
					tBeacon.setPop_times(beacon.getPop_times());
				}
				if (beacon.getIn_distance() != null) {
					tBeacon.setIn_distance(beacon.getIn_distance());
				}
				if (beacon.getActive() != null) {
					tBeacon.setActive(beacon.getActive());
				}
				if (StringUtils.isNotBlank(beacon.getProximityUUID())) {
					tBeacon.setProximityUUID(beacon.getProximityUUID());
				}
				if (StringUtils.isNotBlank(beacon.getMajor())) {
					tBeacon.setMajor(beacon.getMajor());
				}
				if (StringUtils.isNotBlank(beacon.getMinor())) {
					tBeacon.setMinor(beacon.getMinor());
				}
				if (StringUtils.isNotBlank(beacon.getPop_message())) {
					tBeacon.setPop_message(beacon.getPop_message());
				}
				// 判断beacon的绑定的新闻是否和传递的新闻相同
				if (StringUtils.isNotBlank(newsId)) {
					if (tBeacon.getTnews().getNewsId() != Integer.parseInt(newsId)) {
						// 判断绑定的新闻
						TNews tNews = findEntity(TNews.class, Integer.parseInt(newsId));
						if (tNews == null) {
							throw new ValidateException("beacon.newsIsNull");
						}
						// 新闻不是审核通过
						if (!"Published".equals(tNews.getStatus())) {
							throw new ValidateException("beacon.newsIsNotPublished");
						}
						tBeacon.setTnews(tNews);
					}
				}
				updateEntity(tBeacon);
			}
		}
		if (tBeacon != null) {
			return tBeacon;
		} else {
			throw new ValidateException("beacon.beaconUnExist");
		}

	}

	@Override
	public boolean delBeacon(String beaconId, String userId) throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("news.notIsLoginUser");

		// 判断用户
		TUser tuser = findEntity(TUser.class, userId);
		if (tuser == null) {
			throw new ValidateException("user.userUnExist");
		}

		// if (tuser.getRole().indexOf("Console Admin") == -1) {
		// throw new ValidateException("user.userIsNotRole");
		// }
		
		if (StringUtils.isNotBlank(beaconId)) {
			TBeacon tBeacon = findEntity(TBeacon.class, beaconId);
			if (tBeacon != null) {
				return deleteEntity(tBeacon);
			} else {
				throw new ValidateException("beacon.beaconUnExist");
			}
		}
		return false;
	}
	
}
